import React, { useState, useEffect } from 'react';
import {
  Layout,
  Card,
  Form,
  Switch,
  Select,
  Button,
  Space,
  Typography,
  Divider,
  notification,
  Row,
  Col,
  Tabs,
  Alert
} from 'antd';
import {
  SettingOutlined,
  ExperimentOutlined,
  InfoCircleOutlined,
  SaveOutlined,
  ReloadOutlined,
  BugOutlined
} from '@ant-design/icons';
import { ExtensionSettings } from '../types';
import ErrorBoundaryTest from '../components/ErrorBoundaryTest';
import './settings.less';

const { Header, Content } = Layout;
const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

const Settings: React.FC = () => {
  const [form] = Form.useForm();
  const [settings, setSettings] = useState<ExtensionSettings>({
    theme: 'light',
    language: 'zh-CN',
    autoUpdate: true,
    enableNotifications: true
  });
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    try {
      const result = await chrome.storage.sync.get(['settings']);
      if (result.settings) {
        setSettings(result.settings);
        form.setFieldsValue(result.settings);
      }
    } catch (error) {
      console.error('Failed to load settings:', error);
      notification.error({
        message: '加载设置失败',
        description: '无法加载扩展设置，请重试。'
      });
    }
  };

  const handleSave = async (values: ExtensionSettings) => {
    setSaving(true);
    try {
      await chrome.storage.sync.set({ settings: values });
      setSettings(values);
      
      // 通知背景脚本设置已更新
      chrome.runtime.sendMessage({
        type: 'UPDATE_SETTINGS',
        payload: values
      });
      
      notification.success({
        message: '设置已保存',
        description: '您的设置已成功保存。'
      });
    } catch (error) {
      console.error('Failed to save settings:', error);
      notification.error({
        message: '保存失败',
        description: '无法保存设置，请重试。'
      });
    } finally {
      setSaving(false);
    }
  };

  const handleReset = () => {
    const defaultSettings: ExtensionSettings = {
      theme: 'light',
      language: 'zh-CN',
      autoUpdate: true,
      enableNotifications: true
    };
    form.setFieldsValue(defaultSettings);
  };

  const handleDebug = () => {
    console.log('DEBUG button clicked');
    // 测试错误边界
    throw new Error('This is a test error.');
  };

  const renderGeneralSettings = () => (
    <Card title={<><SettingOutlined style={{ marginRight: 8 }} />基本设置</>}>
      <Row gutter={[16, 16]}>
        <Col span={12}>
          <Form.Item
            name="theme"
            label="主题"
            tooltip="选择扩展的显示主题"
          >
            <Select>
              <Option value="light">浅色主题</Option>
              <Option value="dark">深色主题</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="language"
            label="语言"
            tooltip="选择扩展的显示语言"
          >
            <Select>
              <Option value="zh-CN">简体中文</Option>
              <Option value="en-US">English</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="autoUpdate"
            label="自动更新"
            valuePropName="checked"
            tooltip="启用后将自动检查并更新扩展"
          >
            <Switch />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="enableNotifications"
            label="通知"
            valuePropName="checked"
            tooltip="启用后将显示扩展相关通知"
          >
            <Switch />
          </Form.Item>
        </Col>
      </Row>
    </Card>
  );

  const renderAdvancedSettings = () => (
    <Card title={<><ExperimentOutlined style={{ marginRight: 8 }} />高级设置</>}>
      <Alert
        message="实验性功能"
        description="以下功能仍在开发中，可能会影响扩展的稳定性。"
        type="warning"
        showIcon
        style={{ marginBottom: 16 }}
      />
      <Space direction="vertical" style={{ width: '100%' }}>
        <Text type="secondary">高级功能将在后续版本中提供</Text>
      </Space>
    </Card>
  );

  const renderAboutSettings = () => (
    <Card title={<><InfoCircleOutlined style={{ marginRight: 8 }} />关于</>}>
      <Space direction="vertical" style={{ width: '100%' }} size="middle">
        <div>
          <Title level={4}>Chrome 扩展 v1.0.0</Title>
          <Paragraph>
            基于 TypeScript + React + Less + Ant Design 构建的现代化 Chrome 扩展。
          </Paragraph>
        </div>
        
        <Divider />
        
        <div>
          <Title level={5}>功能特性</Title>
          <ul>
            <li>🎨 现代化的用户界面</li>
            <li>🌙 深色/浅色主题支持</li>
            <li>🌍 多语言支持</li>
            <li>📱 响应式设计</li>
            <li>⚡ 高性能构建</li>
          </ul>
        </div>
        
        <Divider />
        
        <div>
          <Title level={5}>技术栈</Title>
          <Space wrap>
            <Text code>TypeScript</Text>
            <Text code>React 18</Text>
            <Text code>Ant Design 5</Text>
            <Text code>Less</Text>
            <Text code>Vite</Text>
            <Text code>Manifest V3</Text>
          </Space>
        </div>
      </Space>
    </Card>
  );

  return (
    <Layout className="settings-layout">
      <Header className="settings-header">
        <div className="header-content">
          <Space>
            <SettingOutlined style={{ fontSize: 24 }} />
            <Title level={3} style={{ margin: 0, color: 'white' }}>
              扩展设置
            </Title>
          </Space>
        </div>
      </Header>
      
      <Content className="settings-content">
        <div className="content-wrapper">
          <Form
            form={form}
            layout="vertical"
            initialValues={settings}
            onFinish={handleSave}
            autoComplete="off"
          >
            <Tabs defaultActiveKey="general" type="card">
              <TabPane tab="基本设置" key="general">
                {renderGeneralSettings()}
              </TabPane>
              <TabPane tab="高级设置" key="advanced">
                {renderAdvancedSettings()}
              </TabPane>
              <TabPane tab="错误测试" key="errorTest">
                <ErrorBoundaryTest />
              </TabPane>
              <TabPane tab="关于" key="about">
                {renderAboutSettings()}
              </TabPane>
            </Tabs>
            
            <Card className="action-card">
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<SaveOutlined />}
                  loading={saving}
                >
                  保存设置
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={handleReset}
                >
                  重置为默认
                </Button>
                <Button
                  icon={<BugOutlined />}
                  onClick={handleDebug}
                >
                  DEBUG
                </Button>
              </Space>
            </Card>
          </Form>
        </div>
      </Content>
    </Layout>
  );
};

export default Settings;